/*
 * @Date: 2022-09-23 10:09:51
 * @LastEditTime: 2023-02-16 16:31:58
 * @Description: 全局路由routers相关逻辑
 */

import { store } from '@/store';
import axios from "@/axios";
import router, { businessRouter, errorRouter } from '@/router'
import { useUserStore } from '@/store/modules/user';
import * as _ from 'lodash'

import { defineStore } from 'pinia';
import {isEmpty} from "@/utils/common";
import {ElMessageBox} from "element-plus";

interface RouterState {
    menuTree: any[],
    hasRoute: boolean,
    sysList: any[],
}

export const useRouterStore = defineStore({
    id: 'app-router',
    state: (): RouterState => ({
        //菜单树
        menuTree: [],
        //是否加载路由
        hasRoute: false,
        sysList: []
    }),
    getters: {
        //获取路由树
        getMenuTree(): any[] {
            return this.menuTree;
        },
        getSysList(): any[] {
            return this.sysList
        }
    },
    actions: {

        /**
         * @description: 修改路由状态
         * @param {any} state
         * @return {*}
         */
        changeRouteStatus(state: any) {
            this.hasRoute = state
            sessionStorage.setItem("hasRoute", state)
        },

        /**
         * @description: 获取路由树
         * @param {any} routers
         * @return {*}
         */
        getRouterTree(routers: any) {
            let result: any = []
            const viteComponentVue = import.meta.glob('@/views/**/**.vue')
            const viteComponentTsx = import.meta.glob('@/views/**/**.tsx')
            const viteComponent = { ...viteComponentVue, ...viteComponentTsx }
            routers.map((route: any) => {
                // let pathArray = route.dm.split('_')
                const path = route.dm.replace(/_/g, "/") // 路由地址
                const name = route.dm // 路由组件名字
                const icon = route.icon // 路由图标
                const desc = route.ms // 路由描述信息
                const lx = route.lx //
                const dzlx = route.dzlx // 路由地址类型
                const dkfs = route.dkfs // 路由打开方式
                const title = route.mc // 路由标题
                const dz = route.dz // 自定义组件地址
                const extend = eval('(' + route.kzxx + ')') // 路由扩展相关信息
                const hidden = extend.hideMenu || false
                const authCode = route.dm // 路由权限码
                const redirect = route.redirect
                let component
                if (lx === '01'||lx==='03') {
                    component = () => import('@/components/Sjdx')
                    if ((!route.children || route.children.length === 0) && dzlx === '01') {
                        // 添加动态路由
                        if (viteComponent[`../../views${dz}/index.vue`]) {
                            component = viteComponent[`../../views${dz}/index.vue`]
                        }
                        else if (viteComponent[`../../views${dz}/index.tsx`]) {
                            component = viteComponent[`../../views${dz}/index.tsx`]
                        }
                    }
                    if ((!route.children || route.children.length === 0) && (dzlx === '02' || dzlx === '05')) {
                        component = () => import('@/views/common/Iframe')
                    }
                }

                if (path) {
                    let item: any = {
                        name,
                        path,
                        redirect,
                        component,
                        meta: {
                            icon,
                            desc,
                            dzlx,
                            dkfs,
                            dz,
                            lx,
                            title,
                            extend,
                            affix: false,
                            hidden,
                            noCache: false,
                            authCode,
                            component,
                            breadcrumb: true
                        },
                        children: []
                    }
                    if (route.children && route.children.length > 0) {
                        item.children = this.getRouterTree(route.children)
                    }
                    result.push(item)
                }
            })
            return result
        },

        /**
         * @description: 设置路由树
         * @return {*}
         * @param zdpdxt
         */
        async setRouter(zdpdxt=false) {
            //查询系统列表
            await axios.post({
                sjdx: {
                    dxdm: "SYS_QX_QTQX",
                },
                sys: {
                    cllx: "getTreeCN",
                },
                yobj: {
                    treeModel: "cds",
                }
            }).then(async (res: any) => {
                this.sysList = res.data.list
                let paths = window.location.hash.split("?")[0].split('/');
                let path1 = paths[1]
                if(path1==='singleHome'){
                    path1 = paths[2];
                }
                if(path1==='sjdx'){
                    path1 = null;
                }
                let treeRoot = useUserStore().getCurrentSystemCode
                if(zdpdxt&&!isEmpty(path1)){
                    treeRoot = path1;
                    useUserStore().setCurrentSystemCode(treeRoot)
                }
                //有系统权限
                let yxtqx = false;
                this.sysList.map(item => {
                    if (item.dm === treeRoot) {
                        axios.setBaseURL(item.ssyydz)
                        yxtqx = true;
                        return
                    }
                })
                this.changeRouteStatus(true)
                if(!yxtqx){
                    //没有该系统权限
                    ElMessageBox.confirm(('没有该系统权限') + '，请确认是否拥有该权限，重新登陆试试', {
                        confirmButtonText: "重新登陆",
                        cancelButtonText: "取消",
                        type: "error"
                    }).then(() => {
                        router.push('/login').then();
                    }).catch(() => {
                        console.log("没有权限，用户没有重新登陆");
                    })
                    return
                }

                //获取菜单树
                await axios.post({
                    sys: {
                        authCode: "QTQX_QXXX",
                        cllx: "cds"
                    },
                    yobj: {
                        treeModel: 'cds',
                        treeRoot: treeRoot,
                    }
                }).then(response => {
                    if (response.status) {
                        let routers:any[] = []
                        if (response.data.length > 0 && response.data[0].children)
                            routers = [...routers, ...this.getRouterTree(response.data[0].children)]
                        // const getTail = (item: any) => item.children && item.children.length > 0 ? item.children.map((m: any) => getTail(m)) : [item]
                        const getTail = (item: any) =>{
                            let r = []
                            if(item.children && item.children.length > 0){
                                r = item.children.map((m: any) => getTail(m))
                            }
                            if(item.meta.lx!=='02'){
                                delete item.children
                                r.push(item)
                            }
                            return r;
                        }
                        const result = _.flattenDeep(routers.map((m: any) => getTail(m)))
                        let singleResult = [] as any[]
                        result.map((item: any) => {
                            singleResult.push({ ...item, ...{ name: 'single_' + item.name } })
                        })

                        for (let i = 0; i < businessRouter.length; i++) {
                            const addRoute = businessRouter[i]
                            if (addRoute && addRoute.children) {
                                if (i === 0) {
                                    addRoute.children = [...addRoute.children, ...singleResult]
                                } else {
                                    addRoute.children = [...addRoute.children, ...result]
                                }
                            }
                            router.addRoute(addRoute)
                        }
                        this.menuTree = routers
                        // 添加最后未匹配的路由
                        for (let j = 0; j < errorRouter.length; j++) {
                            const errorRoute = errorRouter[j]
                            router.addRoute(errorRoute)
                        }
                    }
                }).catch((e) => {
                    console.log("获取菜单失败", e)
                })
                await axios.post({
                    sys: {
                        authCode: "QTQX",
                        cllx: "xtjcxx"
                    }
                }).then(response => {
                    if (response.status) {
                        useUserStore().saveUserInfo(response.data)
                    }
                }).catch((e) => {
                    console.log("获取系统基础信息失败", e)
                })
            });

        },
        /**
         * 自动获取菜单的首页
         * @param menu
         */
        getIndex(menu:any):any{
            if(menu.component){
                return menu;
            }
            if(menu.children){
                return this.getIndex(menu.children[0]);
            }
            console.error("没找到首页")
        }
    },
})

// Need to be used outside the setup
export function useRouterStoreWithOut() {
    return useRouterStore(store);
}
